<template>
  <c-dialog ref="dialog" title="上传图纸" width="60vw" @open="openHandle" @close="closeHandle">
    <c-list ref="form" :model="formData" :rules="formRules" label-width="145px">
      <c-list-item label="图纸任务名称" :value="detail.picTaskName" :span="1/2" />
      <c-list-item label="图纸类型" dict-type-code="PIC_TYPE" :value="detail.picType" :span="1/2" />
      <c-list-item label="选择图纸" prop="shopAttachmentDTOList">
        <c-file-list ref="cUpload" v-model="formData.shopAttachmentDTOList" :rename-fun="renameFun" view-type="image" belong-model="SHOP_DESIGN_PIC" />
      </c-list-item>
      <c-list-item label="图纸性质" prop="pictureNature">
        <c-dict-select v-model="formData.pictureNature" dict-type-code="PICTURE_NATURE" />
      </c-list-item>
      <c-list-item v-if="detail.picType === 'SG'" label="是否完成所有图纸设计" prop="isEndAllDesign">
        <c-dict-select v-model="formData.isEndAllDesign" :include="complateDict(detail.designRange)" dict-type-code="ALL_DRAWING_DESIGNS" />
      </c-list-item>
      <c-list-item v-if="formData.pictureNature==='UPDATES'&&['SG','BC'].includes(detail.picType)" label="是否需要调整出图明细" prop="isNeedAdjustOutpicDetail">
        <c-dict-select v-model="formData.isNeedAdjustOutpicDetail" dict-type-code="BOOLEANS" />
      </c-list-item>
      <c-list-item label="是否需要审批" prop="isNeedApproval">
        <c-dict-select v-model="formData.isNeedApproval" dict-type-code="BOOLEANS" />
      </c-list-item>
      <c-list-item v-if="formData.isNeedApproval==='1'" prop="designPictureApprovalDTOList">
        <div>
          <c-select-dialog
            multiple
            :props="{label: 'userName', value: 'account'}"
            :config="config"
            style="display: inline-block;margin-right:5px;"
            @change="changeHandle"
          >新增审批人</c-select-dialog>
          <c-button type="primary" @click="removeHandle">删除</c-button>
        </div>
        <c-table-box index hide-func checkbox :setting="false" :data="formData.designPictureApprovalDTOList" :table-config="tableConfig" @selection-change="selectionChange" />
      </c-list-item>
      <c-list-item>
        <div class="btn-container">
          <c-button @click="cancelHandle">取消</c-button>
          <c-button key="confirm" type="primary" @click="confirmHandle">确认</c-button>
        </div>
      </c-list-item>
    </c-list>
  </c-dialog>
</template>
<script>
import { postAddPictureMaintain } from '@/api/shopDrawing'
import { SLMDict } from '@/api/dataDict'
export default {
  name: 'Uploader',
  components: {
  },
  props: {
    detail: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    const validateAtt = (r, v, c) => {
      if (v instanceof Array && this.$getFiles(v, this.detail.id).filter(e => e.dr !== 1 && e.dr !== '1').length > 0) {
        c()
      } else {
        c(new Error('请上传图纸'))
      }
    }
    const validateApp = (r, v, c) => {
      if (v instanceof Array && v.length > 0) {
        if (v.every(e => e.steps)) {
          c()
        } else {
          c(new Error('请填写审批步骤'))
        }
      } else {
        c(new Error('请选择审批人'))
      }
    }
    return {
      config: {
        title: '新增审批人',
        interfacePath: '/slm-admin/api/v1/user/domainUser/page',
        method: 'POST',
        setting: [
          {
            prop: 'account',
            title: '账号'
          },
          {
            prop: 'userName',
            title: '审批人'
          },
          {
            prop: 'phone',
            title: '审批人电话'
          },
          {
            prop: 'orgName',
            title: '所属部门'
          }
        ]
      },
      exceptionList: [],
      typeCode: '',
      formData: {
        shopAttachmentDTOList: [],
        pictureNature: '',
        isEndAllDesign: '',
        isNeedAdjustOutpicDetail: '',
        isNeedApproval: '',
        designPictureApprovalDTOList: []
      },
      formRules: {
        shopAttachmentDTOList: [{ required: true, validator: validateAtt, trigger: 'change' }],
        pictureNature: [{ required: true, message: '请选择图纸性质', trigger: 'change' }],
        isEndAllDesign: [{ required: true, message: '请选择是否完成所有图纸设计', trigger: 'change' }],
        isNeedAdjustOutpicDetail: [{ required: true, message: '请选择是否需要调整出图明细', trigger: 'change' }],
        isNeedApproval: [{ required: true, message: '请选择是否需要审批', trigger: 'change' }],
        designPictureApprovalDTOList: [{ required: true, validator: validateApp, trigger: 'change' }]
      },
      tableConfig: {
        setting: [
          {
            prop: 'account',
            label: '账号'
          },
          {
            prop: 'userName',
            label: '审批人'
          },
          {
            prop: 'phone',
            label: '审批人电话'
          },
          {
            prop: 'orgName',
            label: '所属部门'
          },
          {
            prop: 'steps',
            label: '审批步骤',
            render: (h, row) => {
              return h('c-input-number', {
                props: {
                  value: row.steps
                },
                on: {
                  input: v => {
                    this.$set(row, 'steps', v)
                  },
                  change: v => {
                    v = parseInt(v)
                    if (isNaN(v)) {
                      this.$set(row, 'steps', '')
                    }
                    this.sortHandle()
                  }
                }
              })
            }
          }
        ]
      },
      CONST_TYPE: [],
      PIC_DESIGN_SCHEDULE: [],
      selections: []
    }
  },
  computed: {
    versionNumber() {
      const l = this.detail.designPictureMaintainDTOList || []
      if (l.length === 0) {
        return 0
      }
      const t = l.map(e => {
        const v = parseInt(e.picBatchCode.substr(e.picBatchCode.length - 2, 2))
        return !isNaN(v) ? v : 0
      })
      return t.length > 0 ? Math.max(...t) : 0
    }
  },
  watch: {
    formData: {
      handler() {
        this.$refs.form.validate()
      },
      deep: true
    }
  },
  created() {
    this.getDict()
  },
  methods: {
    complateDict(data) {
      if (!data) return ''
      const list = []
      if (data.includes('DOOR')) list.push('1')
      if (data.includes('STORES'))list.push('2')
      list.push('0')
      return list
    },
    openHandle() {
    },
    sortHandle() {
      this.formData.designPictureApprovalDTOList.sort((pre, next) => {
        const p = parseInt(pre.steps)
        const n = parseInt(next.steps)
        return isNaN(p) || isNaN(n) ? 0 : p - n
      })
    },
    validateStep() {
      // eslint-disable-next-line eqeqeq
      if (this.formData.isNeedApproval !== '1') return true
      const t = this.formData.designPictureApprovalDTOList
      for (let i = 0; i < t.length; i++) {
        const item = t[i]
        let step = parseInt(item.steps)
        step = isNaN(step) ? 0 : step
        if (step <= 0) {
          this.$message.warning(`第${i + 1}行审批步骤必须大于0！`)
          return false
        }
        if (i + 1 === t.length) continue
        let _step = parseInt(t[i + 1].steps)
        _step = isNaN(_step) ? 0 : _step
        const diff = _step - step
        if (diff !== 1 && diff !== 0) {
          this.$message.warning(`第${i + 1}行和第${i + 2}行审批步骤不连续！`)
          return false
        }
      }
      const tmp = t.map(e => {
        const tmp = parseInt(e.steps)
        return isNaN(tmp) ? 0 : tmp
      })
      if (Math.min(...tmp) !== 1) {
        this.$message.warning(`审批步骤必须从1开始！`)
        return false
      }
      return true
    },
    confirmHandle() {
      return this.$refs.form.validate().then(() => {
        if (!this.validateStep()) return
        const data = { ...this.detail }
        data.shopAttachmentDTOList = this.$getFiles(this.formData.shopAttachmentDTOList, this.detail.id)
        let stepsNone = false
        if (this.formData.isNeedApproval === '1') {
          data.designPictureApprovalDTOList = this.formData.designPictureApprovalDTOList.map(e => {
            if (e.steps === 0 || e.steps === undefined) {
              stepsNone = true
            }
            return {
              // approvalAdvice	审批意见
              // approvalResult	审批结果：0不通过1通过
              approverCode: e.account, //	审批人编号
              approverName: e.userName, //	审批人名称
              approverPhone: e.phone, //	审批人电话
              deptCode: e.orgCode, //	所属部门编码
              deptName: e.orgName, //	所属部门名称
              pictureMaintainId: this.detail.id, //	设计图纸维护ID
              steps: e.steps //	审批步骤
            }
          })
        }
        if (stepsNone) {
          this.$message.warning('请填写审批步骤！')
          return
        }
        data.pictureNature = this.formData.pictureNature
        data.isEndAllDesign = this.formData.isEndAllDesign
        data.isNeedAdjustOutpicDetail = this.formData.pictureNature === 'UPDATES' ? this.formData.isNeedAdjustOutpicDetail : ''
        data.isNeedApproval = this.formData.isNeedApproval
        let p = Promise.resolve('')
        if (this.detail.picType !== 'SG' && this.formData.isNeedApproval === '0') {
          p = this.$msgbox({
            title: '提示',
            message: '当前图纸不需要审批，确定后将直接完成图纸下发，是否确认？',
            showCancelButton: true,
            type: 'warning'
          })
        } else if (this.detail.picType === 'SG' && this.formData.isNeedApproval === '0') {
          p = this.$msgbox({
            title: '提示',
            message: '当前图纸不需要审批，确定后将直接完成图纸下发，是否确认？',
            showCancelButton: true,
            type: 'warning'
          })
        }

        return p.then(() => {
          return postAddPictureMaintain(data).then(res => {
            this.$message.success('操作成功！')
            this.$refs.dialog.visible = false
            this.$emit('on-success')
          })
        })
      })
    },
    approveHandle(data) {
      for (const d of data) {
        let isHas = false
        for (const t of this.formData.designPictureApprovalDTOList) {
          if (t.account === d.account) {
            isHas = true
            break
          }
        }
        if (isHas) {
          continue
        }
        isHas = false
        this.formData.designPictureApprovalDTOList.push(d)
      }
    },
    selectionChange(v) {
      this.selections = v
    },
    cancelHandle() {
      this.$refs.dialog.visible = false
    },
    getDict() {
      SLMDict('CONST_TYPE').then(res => {
        this.CONST_TYPE = res.data
      })
      SLMDict('PIC_DESIGN_SCHEDULE').then(res => {
        this.PIC_DESIGN_SCHEDULE = res.data
      })
      SLMDict('PIC_TYPE').then(res => {
        this.PIC_TYPE = res.data
      })
    },
    getDictName(dictTypeCode, v) {
      v = this.$split(v)
      const names = []
      for (const d of this[dictTypeCode] || []) {
        if (v.includes(d.dictCode)) {
          names.push(d.dictName)
        }
      }
      return names
    },
    renameFun(file, index, fileList) {
      // 规则：SJ+图纸上传日期+设计公司名称+项目号+门店编码+门店名称（门店建设类型）+办事处名称+图纸进度+图纸任务名称+图纸设计总面积+版本号
      // 示例：sj-20210902①B20210718888K123456781
      // 河北办唐山市乐亭县乐亭镇汇乐城专卖店（整体翻新）摆场图A部分（A\B\C）100㎡V1
      // e.response.data.attachmentName
      const f = file.response.data
      const d = this.detail
      const decorationTypeName = this.getDictName('CONST_TYPE', d.constType) // 翻译
      const picTypeName = this.getDictName('PIC_TYPE', d.picType)
      return `sj-${f.createTime.replace(/-/g, '').replace(/ \d{2}:\d{2}:\d{2}$/, '')}-${d.designUnitName}-${d.constCode}-${d.shopCode}${d.shopName}（${decorationTypeName}）-${d.officeName}-${picTypeName}-${d.picTaskName}-${d.picTotalArea}㎡-V${this.versionNumber + 1}`
    },
    closeHandle() {
      this.typeCode = ''
    },
    removeHandle() {
      if (!this.singleJudge(this.selections, '删除')) {
        return
      }
      const accounts = this.selections.map(e => e.account)
      const t = this.formData.designPictureApprovalDTOList
      this.$set(this.formData, 'designPictureApprovalDTOList', t.filter(e => !accounts.includes(e.account)))
      this.selections = []
    },
    changeHandle(sel) {
      const t = this.formData.designPictureApprovalDTOList.map(e => e.account)
      for (const a of sel) {
        if (t.includes(a.account)) continue
        t.push(a.account)
        this.formData.designPictureApprovalDTOList.push(a)
      }
    }
  }
}
</script>
